/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package parser;
 
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import properties.Property;

/**
 *
 * @author fabio
 */
public class Main {

    public static void main(String[] args) {
        if (args.length < 1) {
            System.err.println("Indicare il file di input");
            System.exit(1);
        }
        File input = new File(args[0]);
        String inputString = "";
        System.out.println("Reading from " + input.getAbsolutePath());
        try {
            if (args.length > 1) {
                File f = new File(args[1]);
                System.out.println("Writing to " + f.getAbsolutePath());//ultima scritta verso l'out
                if (!f.exists()) {
                    f.createNewFile();
                }
                System.setOut(new PrintStream((new FileOutputStream(f))));
            }
            inputString = readFile(input);
        } catch (IOException e) {
            System.err.println("Errore nella lettura dei file");
            System.err.println(e);
            System.exit(1);

        }
        boolean sub = true;
        if (args.length > 2) {
            try {
                sub = Integer.parseInt(args[2]) == 1;
            } catch (Exception e) {
            }
        }
        CharStream cs = new ANTLRInputStream(inputString);
        Lexer lexer = new mccpropertyLexer(cs);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        mccpropertyParser parser = new mccpropertyParser(tokens);
        ParseTree tree = parser.property_set();
        ParseTreeWalker chuck = new ParseTreeWalker();
        Translator listener = new Translator(parser, sub);
        chuck.walk(listener, tree);
        for (Property p : listener.getProperties()) {
            System.out.println("% "+p.getName());
            System.out.println(p.getTranslation());
        }

    }

    private static String readFile(File file) throws IOException {
        //stackoverflow
        try (FileInputStream stream = new FileInputStream(file)) {
            FileChannel fc = stream.getChannel();
            MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            return Charset.defaultCharset().decode(bb).toString();
        }
    }
}
